/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.onsite;

import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.support.AbstractFxmlView;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.onsite.AssetContentView;
import cn.ac.nercis.pes.model.dto.common.TreeNode;
import cn.ac.nercis.pes.model.dto.evaluation.onsite.AssetEvalProcessDTO;
import cn.ac.nercis.pes.service.evaluation.EvaluationRangeService;
import cn.ac.nercis.pes.service.evaluation.EvaluationRecordService;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;

/**
 * 现场测评资产对象组内容管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class AssetGroupController implements Initializable {
    @FXML
    private TabPane assetTabPane;
    @FXML
    private AnchorPane emptyPane;
    @FXML
    private ImageView emptyImageView;
    @FXML
    private Label emptyLabel;

    private final EvaluationRangeService evaluationRangeService;
    private final EvaluationRecordService evaluationRecordService;

    private MenuVO currentAsset;
    private String currentSystemId;

    public AssetGroupController() {
        this.evaluationRangeService = SpringUtils.getBean(EvaluationRangeService.class);
        this.evaluationRecordService = SpringUtils.getBean(EvaluationRecordService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        assetTabPane.getSelectionModel().selectedItemProperty().addListener((observableValue, odlTab, newTab) -> {
            if(Objects.nonNull(newTab) && newTab.getUserData() instanceof MenuVO subAsset){
                loadTabContent(newTab,subAsset);
            }
        });
        ControlUtils.initEmptyImageView(this.emptyImageView,log);
    }

    public void initializeData(String systemId,MenuVO currentAsset){
        LogUtils.info(log, "初始化现场测评资产对象组内容...");
        this.currentSystemId = systemId;
        this.currentAsset = currentAsset;
        this.loadAssetTabData();
    }

    public void refreshAssetGroupState(List<TreeNode> subAssets){
        assetTabPane.getTabs().forEach(tab->{
            MenuVO currentMenu = (MenuVO) tab.getUserData();
            var currentNode = subAssets.stream().filter(sa->StringUtils.equals(sa.getId(),currentMenu.getCode())).findFirst().orElse(null);
            if(Objects.nonNull(currentNode) && currentNode.getData() instanceof AssetEvalProcessDTO process){
                FinishState state = FinishState.NONE;
                if (process.getFinishCount() > 0) {
                    state = process.getFinishCount().equals(process.getCount()) ? FinishState.FINISH : FinishState.INCOMPLETE;
                }
                tab.setGraphic(IconUtils.getGlyph(ControlUtils.finishStateToIcon(state),"tab-item-icon"));
            }
        });
    }

    private void loadAssetTabData() {
        if(CollectionUtils.isNotEmpty(this.currentAsset.getChildren())){
            this.assetTabPane.setVisible(true);
            this.emptyPane.setVisible(false);
            this.initLayerTabData(this.currentAsset.getChildren());
            //this.loadLayerTabProcess();
        }else{
            this.assetTabPane.setVisible(false);
            this.emptyPane.setVisible(true);
            this.emptyLabel.setText("无匹配的系统资产");
        }
    }

    private void initLayerTabData(List<MenuVO> subAssetMenus){
        assetTabPane.getTabs().clear();
        for (MenuVO asset : subAssetMenus){
            Tab layerTab = new Tab(asset.getTitle());
            layerTab.setClosable(false);
            layerTab.setUserData(asset);
            layerTab.setGraphic(IconUtils.getGlyph(ControlUtils.finishStateToIcon(asset.getState()),"tab-item-icon"));
            assetTabPane.getTabs().add(layerTab);
        }
        assetTabPane.getSelectionModel().select(0);
    }

    private void loadTabContent(Tab assetTab,MenuVO subAsset){
        AbstractFxmlView view = AppStore.getEvaluationView(this.currentSystemId, AssetContentView.class);
        assetTab.setContent(Objects.requireNonNull(view).load());
        if (view.getController() instanceof AssetContentController controller) {
            controller.initializeData(this.currentSystemId, subAsset, this.currentAsset);
        }
    }
}